package com.blog.blog.config;

import com.alibaba.fastjson.JSON;
import com.blog.blog.utils.CommunityConstant;
import com.blog.blog.vo.ErrorCode;
import com.blog.blog.vo.Result;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    public void configure(WebSecurity web) throws Exception {
        //忽略静态资源目录下的文件
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权
        http.authorizeRequests()
                .antMatchers(
                        "/articles/listArchives",
                        "/comments/create/change",
                        "/articles/publish",
                        "/articles/findAllPersonalArticle",
                        "/users/getUserInfo",
                        "/tags/findPersonalTag",
                        "/interestTribe/findAllPersonalInterestTribe",
                        "/articles/delArticleById"
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN,
                        AUTHORITY_USER,
                        AUTHORITY_MODERATOR
                )
                .anyRequest().permitAll()
                .and()
                .cors() // 开启跨域支持
                .and()
                .csrf().disable(); //禁用csrf防护
//                .sessionManagement()
//                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        //权限不够时的处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    //未登录
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            System.out.println("未登录");
                            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
                            response.setContentType("application/json;charset=utf-8");
                            response.setHeader("Access-Control-Allow-Credentials","true");
                            response.setHeader("Access-Control-Allow-Origin", "*");
                            response.setHeader("Access-Control-Allow-Headers", "*");
                            response.setHeader("Access-Control-Allow-Methods", "*");
                            PrintWriter writer = response.getWriter();
                            writer.write(JSON.toJSONString(result));
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    //无权限
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(xRequestedWith)) {
                            System.out.println("无权限");
                            Result result = Result.fail(ErrorCode.NO_PERMISSION.getCode(), ErrorCode.NO_PERMISSION.getMsg());
                            response.setContentType("application/json;charset=utf-8");
                            response.setHeader("Access-Control-Allow-Credentials","true");
                            response.setHeader("Access-Control-Allow-Origin", "*");
                            response.setHeader("Access-Control-Allow-Headers", "*");
                            response.setHeader("Access-Control-Allow-Methods", "*");
                            PrintWriter writer = response.getWriter();
                            writer.write(JSON.toJSONString(result));
                        }
                    }
                });
        // Security底层默认会拦截/logout请求,进行退出处理.
        // 覆盖它默认的逻辑,才能执行我们自己的退出代码.
        http.logout().logoutUrl("/securitylogout");
    }

}
